package com.sghy.xcxservice.common;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class Fn {
    /**
     *加密密码
     * @param password 加密的字符串
     * @param encrypt 加密盐
     * @return 加密后的字符串
     */
    public static String[] encryptPassword(String password,String encrypt) {
        String encryptedPassword = null;
        String generatedEncrypt = encrypt != null && !encrypt.isEmpty() ? encrypt : genRandomString(6);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((password.trim() + generatedEncrypt).getBytes());
            byte[] bytes = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte aByte : bytes) {
                sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
            }
            encryptedPassword = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return new String[]{encryptedPassword, generatedEncrypt};
    }
    
    /**
     * 生成指定长度的随机字符串
     * @return
     */
    public static String genRandomString(int len) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder str = new StringBuilder(len);
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < len; i++) {
            int randomIndex = random.nextInt(chars.length());
            str.append(chars.charAt(randomIndex));
        }
        return str.toString();
    }
    
    
    
}
